package com.aiyige.page.my.order.myOrder;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.eventbus.EventOrderChanged;
import com.aiyige.model.OrderEntity;
import com.aiyige.model.eshop.Order;
import com.aiyige.model.eshop.ProductsBackup;
import com.aiyige.model.request.OrderStatusEnum;
import com.aiyige.model.request.SearchBuyerOrdersAllTypeRequest;
import com.aiyige.model.response.SearchBuyerOrderListResponse;
import com.aiyige.page.my.order.adapter.OrderListAdapter;
import com.aiyige.utils.HighLightWordUtil;
import com.aiyige.utils.KeyboardUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.widget.CommonDataView;
import com.aiyige.utils.widget.MyEditText;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import net.cachapa.expandablelayout.ExpandableLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by xiachao on 2017/11/29.
 */
@Route(path = ARouterConfig.SearchMyOrderPage)
public class SearchMyOrderPage extends BaseActivity {

    private static final String TAG = "SearchMyOrderPage";

    public static final int HANDLE_SEARCH = 1;

    @BindView(R.id.cdv)
    CommonDataView cdv;

    OrderListAdapter adapter;

    @BindView(R.id.et_search)
    MyEditText inputEt;

    @BindView(R.id.tv_cancel)
    TextView tvCancel;

    @BindView(R.id.cancelLayout)
    ExpandableLayout cancelLayout;

    //    TextWatcher searchTextWatcher;
//
    HandlerThread searchThread;
    Handler searchHandler;
    Handler mainHandler;

    @Autowired
    public String searchValue;

    public static void start(String searchValue) {
        ARouter.getInstance().build(ARouterConfig.SearchMyOrderPage).withString("searchValue", searchValue).navigation();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_search_my_orders);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        initViews();
    }

    private void initViews() {
        adapter = new OrderListAdapter();
        cdv.config(adapter, null);
        cdv.doRefreshRequest();
        cdv.addItemDecoration(6, R.color.zwcolor_gray_f4f8f9);
        cdv.setRecyclerViewBgColor(ContextCompat.getColor(this, R.color.zwcolor_gray_f4f8f9));
        setAutoRegisterEventBus(true);
        inputEt.getEditText().setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    showSearchResultPanel();
                }
            }
        });
        adapter.setSearchValueCallback( new OrderListAdapter.SearchValueCallback() {
            @Override
            public String getSearchValue() {
                return inputEt.getEditText().getText().toString().trim();
            }
        });
        inputEt.setActionSearch(new MyEditText.ActionCallback() {
            @Override
            public void actionSearch(String value) {
                doSearch(value);
            }
        });
        inputEt.setEditTextHint(getString(R.string.search));
        searchThread = new HandlerThread(TAG + "SearchThread");
        searchThread.start();
        mainHandler = new Handler(Looper.getMainLooper());
        searchHandler = new Handler(searchThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HANDLE_SEARCH:
                        try {
                            if (isEmpty(getSearchValue())) {
                                return;
                            }
                            mainHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    cdv.showLoadingLayout();
                                }
                            });
                            String json = SearchBuyerOrdersAllTypeRequest.newBuilder().keyWord(getSearchValue()).build().execute().body().string();
                            mainHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    cdv.hideCoverLayout();
                                }
                            });
                            if (isEmpty(json)) {
                                return;
                            }
                            final SearchBuyerOrderListResponse response = JsonUtil.toObject(json, SearchBuyerOrderListResponse.class);

                            mainHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    adapter.setNewData(getTypeList(response));
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        break;
                    default:
                        break;
                }
            }
        };
//        inputEt.performClick();
        if (!isEmpty(searchValue)) {
            inputEt.setText(searchValue);
            doSearch(searchValue);
        }
    }

    private List<OrderEntity> getTypeList(SearchBuyerOrderListResponse response) {
        // TODO 转化列表
        List<OrderEntity> orderEntityList = new ArrayList<>();
        if (response != null) {
            // 待付款
            List<Order> nopayList = response.getNopay();
            OrderEntity orderEntityNopay;
            if (!ListUtil.isEmpty(nopayList)) {
                for (int i = 0; i < nopayList.size(); i++) {
                    if (i == 4) {
                        break;
                    }
                    // 把Order给OrderEntity，让原有的OrderEntity去刷新界面从而尽量少的改变代码结构，从而解耦
                    try {
                        Order order = nopayList.get(i);
                        ProductsBackup productsBackup = order.getProductsBackup().get(0);
                        productsBackup.setTitle(HighLightWordUtil.highLight(productsBackup.getTitle(), getSearchValue()));
                    } catch (Exception e) {

                    }
                    orderEntityNopay = new OrderEntity(nopayList.get(i));
                    orderEntityNopay.setShowTypeNameLayout(i == 0);
                    orderEntityNopay.setHasMore(nopayList.size() > 4);
                    orderEntityNopay.setSearch(!TextUtils.isEmpty(getSearchValue()));
                    orderEntityList.add(orderEntityNopay);
                }
            } else {
                orderEntityNopay = new OrderEntity(null);
                orderEntityNopay.setStatus(OrderStatusEnum.STATUS_0_NOPAY.getStatus());
                orderEntityNopay.setHasMore(false);
                orderEntityNopay.setShowTypeNameLayout(true);
                orderEntityNopay.setSearch(!TextUtils.isEmpty(getSearchValue()));
                orderEntityList.add(orderEntityNopay);
            }

            // 待服务/发货
            List<Order> noshipList = response.getNoship();
            OrderEntity orderEntityNoship;
            if (!ListUtil.isEmpty(noshipList)) {
                for (int i = 0; i < noshipList.size(); i++) {
                    if (i == 4) {
                        break;
                    }
                    // 把Order给OrderEntity，让原有的OrderEntity去刷新界面从而尽量少的改变代码结构，从而解耦
                    try {
                        Order order = noshipList.get(i);
                        ProductsBackup productsBackup = order.getProductsBackup().get(0);
                        productsBackup.setTitle(HighLightWordUtil.highLight(productsBackup.getTitle(), getSearchValue()));
                    } catch (Exception e) {

                    }
                    orderEntityNoship = new OrderEntity(noshipList.get(i));
                    orderEntityNoship.setShowTypeNameLayout(i == 0);
                    orderEntityNoship.setHasMore(noshipList.size() > 4);
                    orderEntityNoship.setSearch(!TextUtils.isEmpty(getSearchValue()));
                    orderEntityList.add(orderEntityNoship);
                }
            } else {
                orderEntityNoship = new OrderEntity(null);
                orderEntityNoship.setStatus(OrderStatusEnum.STATUS_3_WAITING_SHIP.getStatus());
                orderEntityNoship.setHasMore(false);
                orderEntityNoship.setShowTypeNameLayout(true);
                orderEntityNoship.setSearch(!TextUtils.isEmpty(getSearchValue()));
                orderEntityList.add(orderEntityNoship);
            }


            // 待确认
            List<Order> unconfirmList = response.getUnconfirm();
            OrderEntity orderEntityUnconfirm;
            if (!ListUtil.isEmpty(unconfirmList)) {
                for (int i = 0; i < unconfirmList.size(); i++) {
                    if (i == 4) {
                        break;
                    }
                    // 把Order给OrderEntity，让原有的OrderEntity去刷新界面从而尽量少的改变代码结构，从而解耦
                    try {
                        Order order = unconfirmList.get(i);
                        ProductsBackup productsBackup = order.getProductsBackup().get(0);
                        productsBackup.setTitle(HighLightWordUtil.highLight(productsBackup.getTitle(), getSearchValue()));
                    } catch (Exception e) {

                    }
                    orderEntityUnconfirm = new OrderEntity(unconfirmList.get(i));
                    orderEntityUnconfirm.setShowTypeNameLayout(i == 0);
                    orderEntityUnconfirm.setHasMore(unconfirmList.size() > 4);
                    orderEntityUnconfirm.setSearch(!TextUtils.isEmpty(getSearchValue()));
                    orderEntityList.add(orderEntityUnconfirm);
                }
            } else {
                orderEntityUnconfirm = new OrderEntity(null);
                orderEntityUnconfirm.setStatus(OrderStatusEnum.STATUS_4_WAITING_AFFIRM.getStatus());
                orderEntityUnconfirm.setHasMore(false);
                orderEntityUnconfirm.setShowTypeNameLayout(true);
                orderEntityUnconfirm.setSearch(!TextUtils.isEmpty(getSearchValue()));
                orderEntityList.add(orderEntityUnconfirm);
            }

            // 退款/售后
            List<Order> aftersaleList = response.getAftersale();
            OrderEntity orderEntity;
            if (!ListUtil.isEmpty(aftersaleList)) {
                for (int i = 0; i < aftersaleList.size(); i++) {
                    if (i == 4) {
                        break;
                    }
                    // 把Order给OrderEntity，让原有的OrderEntity去刷新界面从而尽量少的改变代码结构，从而解耦
                    try {
                        Order order = aftersaleList.get(i);
                        ProductsBackup productsBackup = order.getProductsBackup().get(0);
                        productsBackup.setTitle(HighLightWordUtil.highLight(productsBackup.getTitle(), getSearchValue()));
                    } catch (Exception e) {

                    }
                    orderEntity = new OrderEntity(aftersaleList.get(i));
                    orderEntity.setShowTypeNameLayout(i == 0);
                    orderEntity.setHasMore(aftersaleList.size() > 4);
                    orderEntity.setSearch(!TextUtils.isEmpty(getSearchValue()));
                    orderEntityList.add(orderEntity);
                }
            } else {
                orderEntity = new OrderEntity(null);
                orderEntity.setStatus(OrderStatusEnum.STATUS_6_SALES_RETURN.getStatus());
                orderEntity.setHasMore(false);
                orderEntity.setShowTypeNameLayout(true);
                orderEntity.setSearch(!TextUtils.isEmpty(getSearchValue()));
                orderEntityList.add(orderEntity);
            }

            // 已取消
            List<Order> cancelledList = response.getCancelled();
            OrderEntity orderEntityCancelled;
            if (!ListUtil.isEmpty(cancelledList)) {
                for (int i = 0; i < cancelledList.size(); i++) {
                    if (i == 4) {
                        break;
                    }
                    // 把Order给OrderEntity，让原有的OrderEntity去刷新界面从而尽量少的改变代码结构，从而解耦
                    try {
                        Order order = cancelledList.get(i);
                        ProductsBackup productsBackup = order.getProductsBackup().get(0);
                        productsBackup.setTitle(HighLightWordUtil.highLight(productsBackup.getTitle(), getSearchValue()));
                    } catch (Exception e) {

                    }
                    orderEntityCancelled = new OrderEntity(cancelledList.get(i));
                    orderEntityCancelled.setShowTypeNameLayout(i == 0);
                    orderEntityCancelled.setHasMore(cancelledList.size() > 4);
                    orderEntityCancelled.setSearch(!TextUtils.isEmpty(getSearchValue()));
                    orderEntityList.add(orderEntityCancelled);
                }
            } else {
                orderEntityCancelled = new OrderEntity(null);
                orderEntityCancelled.setStatus(OrderStatusEnum.STATUS_2_CANCEL.getStatus());
                orderEntityCancelled.setHasMore(false);
                orderEntityCancelled.setShowTypeNameLayout(true);
                orderEntityCancelled.setSearch(!TextUtils.isEmpty(getSearchValue()));
                orderEntityList.add(orderEntityCancelled);
            }
        }

        return orderEntityList;
    }

    private String getSearchValue() {
        return isEmpty(inputEt.getEditText().getText().toString().trim()) ? "" : inputEt.getEditText().getText().toString().trim();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventOrderChanged(EventOrderChanged event) {
        if (adapter == null || adapter.getData() == null
                || adapter.getData().isEmpty()
                || event == null
                || TextUtils.isEmpty(event.getOrderEntity().getOrderId())) {
            return;
        }
        List<OrderEntity> list = adapter.getData();
        boolean find = false;
        for (int i = 0; i < list.size(); i++) {
            if (event.getOrderEntity().getOrderId().equals(list.get(i).getOrderId())) {
                list.remove(i);
                if (event.getOrderEntity().getStatus() != OrderEntity.STATUS_DELETED) {
                    list.add(i,event.getOrderEntity());
                }
                find = true;
                break;
            }
        }
        if (find) {
            adapter.notifyDataSetChanged();
        }
        if (cdv != null) {
            cdv.refresh();
        }
    }
    public void showSearchResultPanel() {
        cancelLayout.expand();
        cdv.setVisibility(View.VISIBLE);
    }

    public void hideSearchResultPanel() {
//        cancelLayout.collapse();
//        inputEt.getEditText().clearFocus();
        KeyboardUtil.hideKeyboard(this, inputEt);
//        inputEt.getEditText().setText("");
//        adapter.setNewData(null);
//        cdv.setVisibility(View.INVISIBLE);
        finish();
    }

    private void doSearch(String value) {
        Message msg = Message.obtain();
        msg.what = HANDLE_SEARCH;
        msg.obj = value;
        searchHandler.removeMessages(HANDLE_SEARCH);
        searchHandler.sendMessage(msg);
    }


    @OnClick({R.id.tv_cancel, R.id.cancelLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel:
            case R.id.cancelLayout:
                hideSearchResultPanel();
                break;
        }
    }
}
